package com.myhome.serviceimpl;

import com.myhome.constant.LoginConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author QYiXin
 * @Date 2021 10 05 13 11
 **/
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String loginType = request.getParameter("login_type");
        String grantType = request.getParameter("grant_type");
        if (StringUtils.isEmpty(loginType)) {
            throw new AuthenticationServiceException("无效登录形式");
        }
        if (LoginConstant.GRANT_TYPE.equals(grantType)) {
            s = updateUsername(s,loginType);
        }
        UserDetails userDetails = null;
        try {
            switch (loginType) {
                case LoginConstant.ADMIN_TYPE:
                    userDetails = adminLoadByUserName(s);
                    break;
                case LoginConstant.MEMBER_TYPE:
                    userDetails = memberLoadByUserName(s);
                    break;
                default:
                    throw new AuthenticationServiceException("登录失败");
            }
        }catch (IncorrectResultSizeDataAccessException e){
            throw new UsernameNotFoundException("会员：" + s + "不存在");
        }
        return userDetails;
    }

    private String updateUsername(String s, String loginType) {
        if (LoginConstant.ADMIN_TYPE.equals(loginType)) {
            s = jdbcTemplate.queryForObject(LoginConstant.SELECT_ADMIN_USERNAME, String.class, s);
        }
        if (LoginConstant.MEMBER_TYPE.equals(loginType)) {
            s = jdbcTemplate.queryForObject(LoginConstant.SELECT_MEMBER_USERNAME, String.class, s);
        }
        return s;
    }

    private UserDetails memberLoadByUserName(String s) {
        return jdbcTemplate.queryForObject(LoginConstant.SELECT_USER_INFO, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                if (resultSet.wasNull()) {
                    throw new AuthenticationServiceException("该用户不存在");
                }
                return new User(resultSet.getString("id"), resultSet.getString("password"), true, true, true, true, Arrays.asList(new SimpleGrantedAuthority("ROLE_user")));


            }
        }, s, s);

    }

    private UserDetails adminLoadByUserName(String s) {
        String id = jdbcTemplate.queryForObject(LoginConstant.SELECT_ID, String.class, s);
        User user = null;
        if (StringUtils.isEmpty(id)) {
            throw new AuthenticationServiceException("用户未存在");
        }
        return jdbcTemplate.queryForObject(LoginConstant.SELECT_ADMIN_INFO, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                System.out.println(resultSet.getString("password"));
                if (StringUtils.isEmpty(resultSet)) {
                    throw new AuthenticationServiceException("用户未存在");
                }
                System.out.println(1);
                System.out.println(resultSet.getString("id"));
                System.out.println(resultSet.getString("password"));
                List<String> privileges = jdbcTemplate.queryForList(LoginConstant.SELECT_PRIVILEGE_BY_ID, String.class,id);
                List<SimpleGrantedAuthority> result = privileges.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
                return new User(resultSet.getString("id"), resultSet.getString("password"), true, true, true, true, result);
            }
        }, id);

        /*String adminId = jdbcTemplate.queryForObject(LoginConstant.SELECT_ADMIN_ID, String.class);
        if (!ObjectUtils.isEmpty(adminId)&&adminId.equals(userId)) {
            List<String> privileges = jdbcTemplate.queryForList(LoginConstant.SELECT_PRIVILEGE_BY_ID, String.class);
            result = privileges.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
            new User()
        }*/
    }
}
